#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/25
# @Author  : 邓大大
# @Desc    : API获取行情，pandas分析行情

import ccxt
import talib
import talib as ta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


def df_data(symbol, deal_frequency):
    """
    :param symbol: 代币 （BTC/ETH/...）
    :param deal_frequency: 频率 （1d/1h/1m）
    :return: numpy.ndarray
    """
    my_exchange = ccxt.huobi({
        'timeout': 15000,
        'enableRateLimit': True,
        'proxies': {
            'http': 'http://127.0.0.1:58591',
            'https': 'https://127.0.0.1:58591'}
    })
    period_k = my_exchange.fetch_ohlcv(symbol, timeframe=deal_frequency)
    data_df = pd.DataFrame(period_k)
    data_df.columns = ['Datetime', 'Open', 'High', 'Low', 'Close', 'Vol']
    return data_df


def to_plt(y_list, color='r'):
    plt.plot([i for i in range(0, len(y_list))], y_list, color=color)
    plt.xticks(np.arange(0, len(y_list) + 1, round(len(y_list) / 10, 0)))


def AR(data_df):
    """人气指标： AR(n) = (n日内（H-O）之和)/(n日内 (O-L) 之和) * 100"""

    ar_values = ta.SUM(data_df['High'] - data_df['Open'], timeperiod=20) / ta.SUM(data_df['Open'] - data_df['Low'],
                                                                                  timeperiod=20) * 100
    return ar_values


def MACD(data_df):
    """MACD"""
    a, b, c = talib.MACD(data_df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
    return a, b, c


def BR(data_df):
    """意愿指标:BR(n) = (n日内（H-C）之和/(n日内（C-L）之和) * 100)"""
    highs = data_df['High']
    lows = data_df['Low']
    close_1 = data_df['Close'].shift(-1)
    br_values = ta.SUM(highs - close_1, timeperiod=20) / ta.SUM(close_1 - lows, timeperiod=20) * 100
    return br_values


if __name__ == '__main__':
    d = df_data(symbol='YGG/USDT', deal_frequency='1h')
    ar_values = AR(d)
    br_values = BR(d)
    macd, macd_signal, macdhist = MACD(d)
    to_plt(y_list=list(macd)[-100:], color='y')
    to_plt(y_list=list(macd_signal)[-100:], color='g')
    to_plt(y_list=list(macdhist)[-100:], color='r')
    plt.show()
    # ax = plt.subplot(3, 1, 1,)
    # to_plt(y_list=d['Close'].to_list()[-100:], color='y')
    # start, end = ax.get_ylim()
    # ax.yaxis.set_ticks(np.arange(start, end, 0.1))
    #
    # ax = plt.subplot(3, 1, 2)
    # to_plt(y_list=list(ar_values)[-100:])
    # to_plt(y_list=list(br_values)[-100:], color='g')
    # start, end = ax.get_ylim()
    # ax.yaxis.set_ticks(np.arange(start, end, 100))
    # plt.show()
